<template>
	<div ref="laodingTarget" class="pt-5 text-sm flex justify-center">
		<div class="mb-[2px] text-t-3">{{ text }}</div>
		<base-loading v-if="loading" />
		<div v-else-if="!isFinish && !auto" class="text-primary app-text-link" @click="emits('load')">
			{{ $t(moreTextT) }}
		</div>
		<div v-else-if="isFinish" class="text-primary">{{ $t(noMoreTextT) }}</div>
	</div>
</template>

<script setup lang="ts">
import BaseLoading from '../loading/index.vue'
import { ref, watch } from 'vue'
import { useIntersectionObserver } from '@vueuse/core'

const props = defineProps({
	auto: {
		type: Boolean,
		default: false
	},
	loading: {
		type: Boolean,
		default: false
	},
	isFinish: {
		type: Boolean,
		default: false
	},
	error: {
		type: Boolean,
		default: false
	},
	text: {
		type: String,
		default: ''
	},
	moreTextT: {
		type: String,
		default: 'action.more'
	},
	noMoreTextT: {
		type: String,
		default: 'tip.noMore'
	}
})

const emits = defineEmits(['load'])

// 滚动的元素
const laodingTarget = ref(null)
// 记录当前是否在底部（是否交叉）
const targetIsIntersecting = ref(false)

useIntersectionObserver(laodingTarget, ([{ isIntersecting }]) => {
	// 获取当前交叉状态
	targetIsIntersecting.value = isIntersecting
	// 触发 load
	emitLoad()
})

/**
 * 触发 load
 */
const emitLoad = () => {
	// 当加载更多的视图可见时，加载更多数据
	if (targetIsIntersecting.value && !props.loading && !props.isFinish && props.auto) {
		// 触发加载更多行为
		emits('load')
	}
}

/**
 * 监听 loading 的变化，解决数据加载完成后，首屏未铺满的问题
 */
watch(
	() => props.loading,
	() => {
		if (!props.auto) {
			return
		}
		// 触发 load，延迟处理，等待 渲染和 useIntersectionObserver 的再次触发
		setTimeout(() => {
			emitLoad()
		}, 100)
	}
)
</script>

<style lang="scss" scoped></style>
